package com.zzj.service.impl;



import com.alibaba.fastjson.JSON;
import com.zzj.bean.UserBean;
import com.zzj.dao.UserDao;
import com.zzj.service.UserService;
import com.zzj.utils.JwtUtil;
import com.zzj.utils.Result;
import com.zzj.utils.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class UserserviceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    public Result queryByUnameAndUpassword(String uname, String upassword, HttpServletResponse response) {
        //查询用户信息
        UserBean userBean = userDao.findByUname(uname);

        if (userBean != null && upassword.equals(userBean.getUpassword())) {
            System.out.println(userBean);
            //设置令牌信息
            int uid = userDao.findUidByUname(uname);
            Map<String, Object> info = new HashMap<String, Object>();
            info.put("role", "USER");
            info.put("success", "SUCCESS");
            info.put("uname", uname);
            info.put("uid",uid);
            //生成令牌
            String jwt = JwtUtil.createJWT(UUID.randomUUID().toString(), JSON.toJSONString(info), null);
//            添加cookie
            Cookie cookie = new Cookie("Authorization",jwt);
            response.addCookie(cookie);
            HashMap<String, Object> map = new HashMap<>();
            map.put("user",userBean);
            map.put("token",jwt);
            return new Result(true, StatusCode.OK, "登录成功！", map);
        }
        return new Result(false, StatusCode.LOGINERROR, "账号或者密码错误！");
    }

    @Override
    public Result addUser(UserBean userBean) {
        String uname = userBean.getUname();
        System.out.println(uname);
        UserBean findByUname = userDao.findByUname(uname);
        System.out.println("findByUname = " + findByUname);
        if (findByUname == null){
            userBean.setUstate("1");
            int i = userDao.addUser(userBean);
            System.out.println("i = " + i);
            if (i==1){
                return new Result(true,StatusCode.OK,"注册成功");
            }
            return new Result(false,StatusCode.ERROR,"注册失败");
        }

        return new Result(false,StatusCode.ERROR,"用户名已存在，请重试");
    }
}
